package com.cskaoyan.market.service;

import com.cskaoyan.market.bo.WxOrderCommentBo;
import com.cskaoyan.market.bo.WxOrderListBo;
import com.cskaoyan.market.bo.WxOrderSubmitBo;
import com.cskaoyan.market.db.domain.*;
import com.cskaoyan.market.db.mapper.*;
import com.cskaoyan.market.util.ResponseUtil;
import com.cskaoyan.market.vo.*;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class WxOrderServiceImpl implements WxOrderService {
    @Autowired
    MarketOrderMapper marketOrderMapper;

    @Autowired
    MarketOrderGoodsMapper marketOrderGoodsMapper;

    @Autowired
    MarketChannelMapper marketChannelMapper;

    @Autowired
    SecurityManager securityManager;

    @Autowired
    MarketUserMapper marketUserMapper;

    @Autowired
    MarketAddressMapper marketAddressMapper;

    @Autowired
    MarketCartMapper marketCartMapper;

    @Autowired
    MarketCouponUserMapper marketCouponUserMapper;

    @Autowired
    MarketCouponMapper marketCouponMapper;

    @Autowired
    MarketSystemMapper marketSystemMapper;

    @Autowired
    MarketGoodsMapper marketGoodsMapper;

    @Autowired
    MarketGoodsMapper marketGoodsMapperReal;

    @Autowired
    MarketGoodsProductMapper marketGoodsProductMapper;

    @Autowired
    MarketCommentMapper marketCommentMapper;


    @Autowired
    FlashMapFactory flashMapFactory;

    /*
     * 101: '未付款', 102: '用户取消', 103: '系统取消', 201: '已付款', 202: '申请退款',
     * 203: '已退款', 301: '已发货', 401: '用户收货', 402: '系统收货'
     * */


    public Map<Integer, String> inputMap() {
        Map<Integer, String> statusCode = new HashMap<>();
        statusCode.put(101, "未付款");
        statusCode.put(102, "用户取消");
        statusCode.put(103, "系统取消");
        statusCode.put(201, "已付款");
        statusCode.put(202, "申请退款");
        statusCode.put(203, "已退款");
        statusCode.put(301, "已发货");
        statusCode.put(401, "用户收货");
        statusCode.put(402, "系统收货");

        return statusCode;
    }

    @Override
    public Object list(MarketUser user,WxOrderListBo wxOrderListBo) {

        Map<Integer, String> integerStringMap = inputMap();
        Integer limit = wxOrderListBo.getLimit();
        Integer page = wxOrderListBo.getPage();
        Integer showType = wxOrderListBo.getShowType();
        Integer filter = null;
        if (showType == 0) {
            filter = 0;

//            marketBrandExample.setOrderByClause(sort + " " + order);
            Object okList = getOrderList(user.getId(),page, limit, integerStringMap, filter);


            return okList;
        }
        //待付款101
        if (showType == 1) {
            filter = 101;

            Object okList = getOrderList(user.getId(),page, limit, integerStringMap, filter);


            return okList;
        }
        //代发货201
        if (showType == 2) {
            filter = 201;

            Object okList = getOrderList(user.getId(),page, limit, integerStringMap, filter);


            return okList;
        }
        //待收货301
        if (showType == 3) {
            filter = 301;

            Object okList = getOrderList(user.getId(),page, limit, integerStringMap, filter);


            return okList;
        }
        //待评价401
        if (showType == 4) {
            filter = 401;

            Object okList = getOrderList(user.getId(),page, limit, integerStringMap, filter);


            return okList;
        }


        return ResponseUtil.fail();
    }

    @Override
    public WxOrderDetailVo detail(Integer orderId) {
        List<MarketOrder> marketOrders =
                marketOrderMapper.selectByExampleSelective(new MarketOrderExample());

        List<MarketOrderGoods> marketOrderGoods =
                marketOrderGoodsMapper.selectByExampleSelective(new MarketOrderGoodsExample());
        List<MarketChannel> marketChannels = marketChannelMapper.selectAll();
        Map<String, String> expCode = getExpCode(marketChannels);
        Map<Integer, List<MarketOrderGoods>> integerListMap = groupByOrderId(marketOrderGoods);

        Map<Integer, String> integerStringMap = inputMap();
        WxOrderDetailVo wxOrderDetailVo = new WxOrderDetailVo();
        for (MarketOrder marketOrder : marketOrders) {
            if (orderId == marketOrder.getId() && marketOrder.getDeleted() != true) {

                wxOrderDetailVo.setOrderGoods(integerListMap.get(orderId));

                OrderInfoVo orderInfoVo = new OrderInfoVo(
                        marketOrder.getActualPrice(),
                        marketOrder.getAddTime(),
                        marketOrder.getAddress(),
                        marketOrder.getAftersaleStatus(),
                        marketOrder.getConsignee(),
                        marketOrder.getCouponPrice(),
                        marketOrder.getShipChannel(),
                        expCode.get(marketOrder.getShipChannel()),
                        marketOrder.getShipSn(),
                        marketOrder.getFreightPrice(),
                        marketOrder.getOrderPrice(),
                        statusGetHandleOption(marketOrder.getOrderStatus()),
                        marketOrder.getId(),
                        marketOrder.getMessage(),
                        marketOrder.getMobile(),
                        marketOrder.getOrderSn(),
                        integerStringMap.get((int) marketOrder.getOrderStatus())
                );


//                if()
                wxOrderDetailVo.setOrderInfo(orderInfoVo);
            }

        }
        return wxOrderDetailVo;

    }



    @Override
    public Integer getUserID() {
        SecurityUtils.setSecurityManager(securityManager);
        Subject subject = SecurityUtils.getSubject();
        Session session = subject.getSession();
        MarketUser user = (MarketUser) session.getAttribute("user");
        MarketUserExample marketUserExample = new MarketUserExample();
        MarketUserExample.Criteria criteria = marketUserExample.createCriteria();
        criteria.andUsernameEqualTo(user.getUsername());
        MarketUser marketUser = marketUserMapper.selectByExample(marketUserExample).get(0);

        Integer userId = marketUser.getId();

        return userId;
    }
    @Transactional
    @Override
    public Integer updateOrder(Integer orderId, Short statusCode) {
        MarketOrderExample marketOrderExample = new MarketOrderExample();
        MarketOrderExample.Criteria criteria = marketOrderExample.createCriteria();
        criteria.andIdEqualTo(orderId);
        MarketOrder marketOrder = new MarketOrder();
        if (statusCode != null) {
            marketOrder.setOrderStatus(statusCode);
            if(statusCode==202){
                marketOrder.setRefundTime(LocalDateTime.now());
            }
            if(statusCode==201){
                marketOrder.setUpdateTime(LocalDateTime.now());
            }
            if(statusCode==401){
                marketOrder.setConfirmTime(LocalDateTime.now());
                marketOrder.setUpdateTime(LocalDateTime.now());
            }
        } else {
            marketOrder.setDeleted(true);
        }

        int i = marketOrderMapper.updateByExampleSelective(marketOrder, marketOrderExample);
        if(i==1){
            return 0;
        }
        return 1;
    }


    @Transactional
    @Override
    public Integer submit(WxOrderSubmitBo wxOrderSubmitBo, Integer userId) {


        if (wxOrderSubmitBo == null) {
            return 1;
        }

        Integer addressId = wxOrderSubmitBo.getAddressId();
        Integer couponId = wxOrderSubmitBo.getCouponId();

//        System.out.println(marketAddress);

        MarketCouponUser marketCouponUser = null;
        MarketCoupon marketCoupon = null;
        Integer userCouponId = wxOrderSubmitBo.getUserCouponId();
        MarketCouponUserExample marketCouponUserExample = new MarketCouponUserExample();
//        marketCouponUserExample.createCriteria().andIdEqualTo(userCouponId);



            if (userCouponId != -1 && userCouponId != 0 && couponId != 0) {

                marketCouponUser = marketCouponUserMapper.selectByExample(marketCouponUserExample).get(0);

                MarketCouponExample marketCouponExample = new MarketCouponExample();
                marketCouponExample.createCriteria().andIdEqualTo(couponId);
                marketCoupon = marketCouponMapper.selectByExample(marketCouponExample).get(0);
            }
            if (couponId == 0) {
                marketCouponUser = marketCouponUserMapper.selectByExample(marketCouponUserExample).get(0);
                MarketCouponExample marketCouponExample = new MarketCouponExample();
                marketCouponExample.createCriteria().andIdEqualTo(marketCouponUser.getCouponId());
                marketCoupon = marketCouponMapper.selectByExample(marketCouponExample).get(0);
            }


            MarketAddressExample marketAddressExample = new MarketAddressExample();
            marketAddressExample.createCriteria().andIdEqualTo(addressId);
            MarketAddress marketAddress = marketAddressMapper.selectByExample(marketAddressExample).get(0);

            MarketSystemExample marketSystemExample1 = new MarketSystemExample();
            marketSystemExample1.createCriteria().andKeyNameEqualTo("market_express_freight_min");
            MarketSystem marketExpressFreightMin = marketSystemMapper.selectOneByExample(marketSystemExample1);

            MarketSystemExample marketSystemExample2 = new MarketSystemExample();
            marketSystemExample2.createCriteria().andKeyNameEqualTo("market_express_freight_value");
            MarketSystem marketExpressFreightValue = marketSystemMapper.selectOneByExample(marketSystemExample2);

            MarketOrder marketOrder = new MarketOrder();
//todo
            if (wxOrderSubmitBo.getCartId() == 0) {

                MarketCartExample marketCartExample = new MarketCartExample();
                marketCartExample.createCriteria().andUserIdEqualTo(userId);
                List<MarketCart> marketCarts = marketCartMapper.selectByExample(marketCartExample);

//            System.out.println(marketCarts);
                //获取cart的GoodsId
                List<Integer> getCartToGoodsIds = new ArrayList<>();
                for (MarketCart marketCart : marketCarts) {
                    getCartToGoodsIds.add(marketCart.getGoodsId());
                }


                //根据Id获取Goods以及GoodsProduct信息
                List<MarketGoods> marketGoodsList = new ArrayList<>();
                List<MarketGoodsProduct> marketGoodsProductList = new ArrayList<>();
                for (Integer getCartToGoodsId : getCartToGoodsIds) {
                    MarketGoodsExample marketGoodsExample = new MarketGoodsExample();
                    marketGoodsExample.createCriteria().andIdEqualTo(getCartToGoodsId);
                    MarketGoods marketGoods = marketGoodsMapperReal.selectByExample(marketGoodsExample).get(0);
                    marketGoodsList.add(marketGoods);

                    MarketGoodsProductExample marketGoodsProductExample = new MarketGoodsProductExample();
                    marketGoodsProductExample.createCriteria().andGoodsIdEqualTo(getCartToGoodsId);
                    MarketGoodsProduct marketGoodsProduct = marketGoodsProductMapper.selectByExample(marketGoodsProductExample).get(0);
                    marketGoodsProductList.add(marketGoodsProduct);
                }
                //获取订单信息
                String address = marketAddress.getProvince() + marketAddress.getCity() +
                        marketAddress.getCounty() + marketAddress.getAddressDetail();

                String orderSn = getNowTimetoString();

                marketOrder.setUserId(userId);

                marketOrder.setOrderSn(orderSn);
                marketOrder.setOrderStatus((short) 101);
                marketOrder.setAftersaleStatus((short) 0);
                marketOrder.setConsignee(marketAddress.getName());
                marketOrder.setMobile(marketAddress.getTel());
                marketOrder.setAddress(address);
                marketOrder.setMessage(wxOrderSubmitBo.getMassage());
                if (userCouponId != -1) {
                    marketOrder.setCouponPrice(marketCoupon.getDiscount());
                } else {
                    marketOrder.setCouponPrice(new BigDecimal(0));
                }
                //计算总价
                BigDecimal totalPrice = BigDecimal.ZERO;
                for (MarketCart marketCart : marketCarts) {
                    BigDecimal price = null;
                    if (marketCart.getNumber() > 1) {
                        int number = marketCart.getNumber();
                        price = marketCart.getPrice();
                        price = price.multiply(BigDecimal.valueOf(number));

                    } else {
                        price = marketCart.getPrice();
                    }

                    totalPrice = totalPrice.add(price);

                }

//            判断快递运费
                marketOrder.setGoodsPrice(totalPrice);
                if (totalPrice.compareTo(new BigDecimal(Double.parseDouble(marketExpressFreightMin.getKeyValue()))) == 1) {
                    marketOrder.setFreightPrice(new BigDecimal(0));
                } else {
                    marketOrder.setFreightPrice(new BigDecimal(Double.parseDouble(marketExpressFreightValue.getKeyValue())));
                    marketOrder.setActualPrice(totalPrice.subtract(marketOrder.getFreightPrice()));
                }
                marketOrder.setOrderPrice(totalPrice);

                //是否使用优惠券
                if (userCouponId != -1) {
                    //判断优惠券是否可用
                    if (marketCouponUser.getStatus() == 0 || marketCoupon != null) {
                        marketOrder.setActualPrice(marketOrder.getOrderPrice().subtract(marketCoupon.getDiscount()));

                        MarketCouponUser marketCouponUser1 = new MarketCouponUser();
                        marketCouponUser1.setId(marketCouponUser.getId());
                        marketCouponUser1.setStatus((short) 1);
                        marketCouponUser1.setOrderId(marketOrder.getId());
                        marketCouponUser1.setUsedTime(LocalDateTime.now());
                        marketCouponUserMapper.updateByPrimaryKeySelective(marketCouponUser1);

                    } else {
                        marketOrder.setActualPrice(marketOrder.getOrderPrice());
                    }
                    marketOrder.setCouponPrice(marketCoupon.getDiscount());
                } else {
                    marketOrder.setCouponPrice(new BigDecimal(0));
                    marketOrder.setActualPrice(marketOrder.getOrderPrice());
                }
                marketOrder.setAddTime(LocalDateTime.now());
                marketOrder.setUpdateTime(LocalDateTime.now());

                marketOrder.setIntegralPrice(new BigDecimal(0));
                marketOrder.setGrouponPrice(new BigDecimal(0));

                marketOrder.setComments((short) marketCarts.size());

//            将order写入数据库
                marketOrderMapper.insertSelective(marketOrder);

                //获取OrderGoodsList
                List<MarketOrderGoods> marketOrderGoodsList = new ArrayList<>();
                for (MarketGoods marketGoods : marketGoodsList) {
//                System.out.println(marketGoods);
                    //创建商品订单
                    MarketOrderGoods marketOrderGoods = new MarketOrderGoods();

                    marketOrderGoods.setOrderId(marketOrder.getId());
                    marketOrderGoods.setGoodsId(marketGoods.getId());
                    marketOrderGoods.setGoodsName(marketGoods.getName());
                    marketOrderGoods.setGoodsSn(marketGoods.getGoodsSn());
                    MarketCommentExample marketCommentExample = new MarketCommentExample();
                    marketCommentExample.createCriteria().andValueIdEqualTo(marketOrderGoods.getGoodsId());
                    MarketComment marketComment = null;
                    marketComment = marketCommentMapper.selectOneByExample(marketCommentExample);
                    if (marketComment == null) {
                        marketOrderGoods.setComment(0);

                    } else {
                        marketOrderGoods.setComment(marketComment.getId());
                    }
                    marketOrderGoods.setAddTime(LocalDateTime.now());
                    marketOrderGoods.setUpdateTime(LocalDateTime.now());
//                System.out.println("校验前ID："+marketOrderGoods.getGoodsId());

                    for (MarketGoodsProduct marketGoodsProduct : marketGoodsProductList) {
//                System.out.println(marketGoodsProduct);
                        if (marketGoodsProduct.getGoodsId().equals(marketOrderGoods.getGoodsId())) {
//                        System.out.println("校验后ID："+marketGoodsProduct.getGoodsId());
                            marketOrderGoods.setProductId(marketGoodsProduct.getId());
                            marketOrderGoods.setSpecifications(marketGoodsProduct.getSpecifications());
                            marketOrderGoods.setPicUrl(marketGoods.getPicUrl());
                        }
                    }

                    for (MarketCart marketCart : marketCarts) {
                        if (marketCart.getGoodsId().equals(marketOrderGoods.getGoodsId())) {
//                        System.out.println("校验后ID："+marketCart.getGoodsId());
                            marketOrderGoods.setNumber(marketCart.getNumber());
                            marketOrderGoods.setPrice(marketCart.getPrice());
                            marketOrderGoods.setPicUrl(marketCart.getPicUrl());
                        }
                    }
                    System.out.println(marketOrderGoods);
                    marketOrderGoodsList.add(marketOrderGoods);
                }

                //将购物车中的订单商品写入数据库
                for (MarketOrderGoods marketOrderGoods : marketOrderGoodsList) {
                    marketOrderGoodsMapper.insertSelective(marketOrderGoods);
                }

                //删除购物车的里已被结束的数据

                for (Integer getCartToGoodsId : getCartToGoodsIds) {
                    MarketCartExample marketCartExample1 = new MarketCartExample();
                    marketCartExample1.createCriteria().andGoodsIdEqualTo(getCartToGoodsId);
                    marketCartMapper.deleteByExample(marketCartExample1);
                }

                return marketOrder.getId();
            }


            MarketCartExample marketCartExample = new MarketCartExample();
            marketCartExample.createCriteria().andIdEqualTo(wxOrderSubmitBo.getCartId());
            MarketCart marketCart = marketCartMapper.selectByExample(marketCartExample).get(0);

            String address = marketAddress.getProvince() + marketAddress.getCity() +
                    marketAddress.getCounty() + marketAddress.getAddressDetail();
            String orderSn = getNowTimetoString();


            marketOrder.setUserId(marketAddress.getUserId());
            marketOrder.setOrderSn(orderSn);
            marketOrder.setOrderStatus((short) 101);
            marketOrder.setAftersaleStatus((short) 0);
            marketOrder.setConsignee(marketAddress.getName());
            marketOrder.setMobile(marketAddress.getTel());
            marketOrder.setAddress(address);

            marketOrder.setMessage(wxOrderSubmitBo.getMassage());
            BigDecimal price = marketCart.getPrice();
            if (marketCart.getNumber() > 1) {
                int number = marketCart.getNumber();

                price = price.multiply(new BigDecimal(number));
                marketOrder.setGoodsPrice(price);
            } else {
                marketOrder.setGoodsPrice(price);
            }
            marketOrder.setOrderPrice(marketOrder.getGoodsPrice());


            if (marketOrder.getGoodsPrice().compareTo(new BigDecimal(Double.parseDouble(marketExpressFreightMin.getKeyValue()))) == 1) {
                marketOrder.setFreightPrice(new BigDecimal(0));
                marketOrder.setActualPrice(marketOrder.getOrderPrice());
            } else {
                marketOrder.setFreightPrice(new BigDecimal(Double.parseDouble(marketExpressFreightValue.getKeyValue())));
                marketOrder.setActualPrice(marketOrder.getGoodsPrice().add(marketOrder.getFreightPrice()));
            }


            //是否使用优惠券
            if (marketCouponUser != null) {
                //判断优惠券是否可用
                if (marketCouponUser.getStatus() == 0) {
                    marketOrder.setActualPrice(marketOrder.getActualPrice().subtract(marketCoupon.getDiscount()));

                    MarketCouponUser marketCouponUser1 = new MarketCouponUser();
                    marketCouponUser1.setId(marketCouponUser.getId());
                    marketCouponUser1.setStatus((short) 1);
                    marketCouponUser1.setOrderId(marketOrder.getId());
                    marketCouponUser1.setUsedTime(LocalDateTime.now());
                    marketCouponUserMapper.updateByPrimaryKeySelective(marketCouponUser1);

                }
                marketOrder.setCouponPrice(marketCoupon.getDiscount());
            } else {
                marketOrder.setCouponPrice(new BigDecimal(0));
            }

            marketOrder.setAddTime(LocalDateTime.now());
            marketOrder.setUpdateTime(LocalDateTime.now());

            marketOrder.setIntegralPrice(new BigDecimal(0));
            marketOrder.setGrouponPrice(new BigDecimal(0));

            marketOrder.setComments((short) 1);

            //将order写入数据库
            marketOrderMapper.insertSelective(marketOrder);

            MarketGoodsExample marketGoodsExample = new MarketGoodsExample();
            marketGoodsExample.createCriteria().andIdEqualTo(marketCart.getGoodsId());
            MarketGoods marketGoods = marketGoodsMapperReal.selectByExample(marketGoodsExample).get(0);


            MarketOrderGoods marketOrderGoods = new MarketOrderGoods();
            marketOrderGoods.setOrderId(marketOrder.getId());
            marketOrderGoods.setGoodsId(marketGoods.getId());
            marketOrderGoods.setGoodsName(marketGoods.getName());
            marketOrderGoods.setGoodsSn(marketGoods.getGoodsSn());

            MarketGoodsProductExample marketGoodsProductExample = new MarketGoodsProductExample();
            marketGoodsProductExample.createCriteria().andGoodsIdEqualTo(marketOrderGoods.getGoodsId());
            MarketGoodsProduct marketGoodsProduct = marketGoodsProductMapper.selectByExample(marketGoodsProductExample).get(0);

            marketOrderGoods.setProductId(marketGoodsProduct.getId());
            marketOrderGoods.setNumber(marketCart.getNumber());
            marketOrderGoods.setPrice(marketCart.getPrice());
            marketOrderGoods.setSpecifications(marketGoodsProduct.getSpecifications());
            marketOrderGoods.setPicUrl(marketGoods.getPicUrl());

            MarketCommentExample marketCommentExample = new MarketCommentExample();
            marketCommentExample.createCriteria().andValueIdEqualTo(marketOrderGoods.getGoodsId());
            marketOrderGoods.setComment(0);
            marketOrderGoods.setAddTime(LocalDateTime.now());
            marketOrderGoods.setUpdateTime(LocalDateTime.now());


            marketOrderGoodsMapper.insertSelective(marketOrderGoods);

            MarketCartExample marketCartExample1 = new MarketCartExample();
            marketCartExample1.createCriteria().andIdEqualTo(wxOrderSubmitBo.getCartId()).andUserIdEqualTo(userId);
            marketCartMapper.deleteByExample(marketCartExample1);
            return marketOrder.getId();
        }

        @Override
        public MarketOrderGoods goods (Integer orderId, Integer goodsId){
            MarketOrderGoodsExample marketOrderGoodsExample = new MarketOrderGoodsExample();
            marketOrderGoodsExample.createCriteria().andOrderIdEqualTo(orderId).andGoodsIdEqualTo(goodsId);
            MarketOrderGoods marketOrderGoods = marketOrderGoodsMapper.selectByExampleSelective(marketOrderGoodsExample).get(0);
            return marketOrderGoods;
        }

        @Transactional
        @Override
        public Integer comment (WxOrderCommentBo wxOrderCommentBo){

            MarketOrderGoodsExample marketOrderGoodsExample = new MarketOrderGoodsExample();
            marketOrderGoodsExample.createCriteria().andIdEqualTo(wxOrderCommentBo.getOrderGoodsId());
            MarketOrderGoods marketOrderGoods = marketOrderGoodsMapper.selectByExampleSelective(marketOrderGoodsExample).get(0);

            MarketOrderExample marketOrderExample = new MarketOrderExample();
            marketOrderExample.createCriteria().andIdEqualTo(marketOrderGoods.getOrderId());
            MarketOrder marketOrder = marketOrderMapper.selectByExample(marketOrderExample).get(0);

            marketOrder.setId(marketOrderGoods.getOrderId());
            marketOrder.setComments((short) (marketOrder.getComments() - (short) 1));
            marketOrderMapper.updateByPrimaryKeySelective(marketOrder);


            MarketComment marketComment = new MarketComment();
            marketComment.setContent(wxOrderCommentBo.getContent());
            marketComment.setStar(wxOrderCommentBo.getStar());
            marketComment.setPicUrls(wxOrderCommentBo.getPicUrls());
            marketComment.setValueId(marketOrderGoods.getGoodsId());
            marketComment.setUserId(marketOrder.getUserId());
            marketComment.setHasPicture(wxOrderCommentBo.getHasPicture());
            marketComment.setAddTime(LocalDateTime.now());
            marketComment.setUpdateTime(LocalDateTime.now());


            int code = marketCommentMapper.insertSelective(marketComment);
            marketOrderGoods.setComment(marketComment.getId());

            marketOrderGoodsMapper.updateByExampleSelective(marketOrderGoods, marketOrderGoodsExample);
            if (code == 1) {
                return 0;
            }

            return 1;
        }


        private String getNowTimetoString () {
            LocalDateTime ldt = LocalDateTime.now();
            String year = String.valueOf(ldt.getYear());
            String monthValue = String.valueOf(ldt.getMonthValue());
            String dayOfMonth = String.valueOf(ldt.getDayOfMonth());
            String minute = String.valueOf(ldt.getMinute());
            String second = String.valueOf(ldt.getSecond());
            String result = year + monthValue + dayOfMonth + minute + second;
            return result;
        }


        private Map<String, String> getExpCode (List < MarketChannel > marketChannels) {
            Map<String, String> map = new HashMap<>();
            for (MarketChannel marketChannel : marketChannels) {
                map.put(marketChannel.getName(), marketChannel.getDetail());
            }

            return map;
        }

//Integer userId,Integer page,Integer limit,Map<Integer, String> integerStringMap, Integer filter

        private Object getOrderList (Integer userId,Integer page,Integer limit,Map<Integer, String> integerStringMap, Integer filter){
            MarketOrderExample marketOrderExample = new MarketOrderExample();
            List<MarketOrder> marketOrders = null;

//        boolean orderListIsFlash = (boolean) flashMapFactory.getValue("orderListIsFlash");
//        if (orderListIsFlash) {
//            MarketOrderExample.Criteria criteria = marketOrderExample.createCriteria();
//            criteria.andUserIdEqualTo(userId);
//            marketOrders = marketOrderMapper.selectByExampleSelective(new MarketOrderExample());
//            flashMapFactory.putValue("flashOrderList",marketOrders);
//        }
            List<MarketOrder> flashOrderList = (List<MarketOrder>) flashMapFactory.getValue("flashOrderList");
            marketOrders = flashOrderList;


            List<MarketOrderGoods> marketOrderGoods = marketOrderGoodsMapper.selectByExampleSelective(new MarketOrderGoodsExample());

            List<WxOrderResultListVo> wxOrderResultListVos = getWxOrderResultListVos(integerStringMap, filter, marketOrderGoods, marketOrders);


            WxOrderResultListOkVo resultOk = getOkResult(page, limit,wxOrderResultListVos);

            return ResponseUtil.ok(resultOk);
        }

        private List<WxOrderResultListVo> getWxOrderResultListVos (Map < Integer, String > integerStringMap, Integer
        filter, List < MarketOrderGoods > marketOrderGoods, List < MarketOrder > marketOrders){
            Map<Integer, List<MarketOrderGoods>> integerListMap = groupByOrderId(marketOrderGoods);

            List<WxOrderResultListVo> wxOrderResultListVos = new ArrayList<>();

            for (MarketOrder marketOrder : marketOrders) {
                if (filter == 0 && marketOrder.getDeleted() != true) {
                    WxOrderResultListVo tempListVo = new WxOrderResultListVo(
                            marketOrder.getActualPrice(),
                            marketOrder.getAftersaleStatus(),
                            integerListMap.get(marketOrder.getId()),
                            statusGetHandleOption(marketOrder.getOrderStatus()),
                            marketOrder.getId(),
                            "false",
                            marketOrder.getOrderSn(),
                            integerStringMap.get((int) marketOrder.getOrderStatus())
                    );
                    wxOrderResultListVos.add(tempListVo);
                    continue;
                }
                if (filter == (int) marketOrder.getOrderStatus() && marketOrder.getDeleted() != true) {
                    WxOrderResultListVo tempListVo = new WxOrderResultListVo(
                            marketOrder.getActualPrice(),
                            marketOrder.getAftersaleStatus(),
                            integerListMap.get(marketOrder.getId()),
                            statusGetHandleOption(marketOrder.getOrderStatus()),
                            marketOrder.getId(),
                            "false",
                            marketOrder.getOrderSn(),
                            integerStringMap.get((int) marketOrder.getOrderStatus())
                    );
                    wxOrderResultListVos.add(tempListVo);
                }
            }
            return wxOrderResultListVos;
        }

        private WxOrderResultListOkVo getOkResult ( Integer page, Integer limit, List < WxOrderResultListVo > wxOrderResultListVos){
            int realpages = wxOrderResultListVos.size() / limit;
            double pages = (double) wxOrderResultListVos.size() / (double) limit;
            if (pages > realpages) {
                realpages = realpages + 1;
                return new WxOrderResultListOkVo(limit, wxOrderResultListVos, page, realpages, wxOrderResultListVos.size());
            }

            return new WxOrderResultListOkVo(limit, wxOrderResultListVos, page, realpages, wxOrderResultListVos.size());
        }

        private Map<Integer, List<MarketOrderGoods>> groupByOrderId (List < MarketOrderGoods > marketOrderGoods) {
            Map<Integer, List<MarketOrderGoods>> map = new HashMap<Integer, List<MarketOrderGoods>>();
            for (MarketOrderGoods marketOrderGood : marketOrderGoods) {
                Integer orderId = marketOrderGood.getOrderId();

                List<MarketOrderGoods> list = map.get(orderId);
                if (list == null) {
                    list = new ArrayList<MarketOrderGoods>();
                }
                list.add(marketOrderGood);
                map.put(orderId, list);
            }
            return map;
        }

        public HandleOptionVo statusGetHandleOption (Short num){
            HandleOptionVo handleOptionVo = new HandleOptionVo();

            if (num == 201) {
                handleOptionVo.setAftersale(false);
                handleOptionVo.setCancel(false);
                handleOptionVo.setComment(false);
                handleOptionVo.setConfirm(false);
                handleOptionVo.setDelete(false);
                handleOptionVo.setPay(false);
                handleOptionVo.setRebuy(false);
                handleOptionVo.setRefund(true);
            }
            if (num == 301) {
                handleOptionVo.setAftersale(false);
                handleOptionVo.setCancel(false);
                handleOptionVo.setComment(false);
                handleOptionVo.setConfirm(true);
                handleOptionVo.setDelete(false);
                handleOptionVo.setPay(false);
                handleOptionVo.setRebuy(false);
                handleOptionVo.setRefund(true);
            }
            if (num == 401) {
                handleOptionVo.setAftersale(true);
                handleOptionVo.setCancel(false);
                handleOptionVo.setComment(true);
                handleOptionVo.setConfirm(false);
                handleOptionVo.setDelete(true);
                handleOptionVo.setPay(false);
                handleOptionVo.setRebuy(true);
                handleOptionVo.setRefund(false);
            }
            if (num == 202) {
                handleOptionVo.setAftersale(false);
                handleOptionVo.setCancel(false);
                handleOptionVo.setComment(false);
                handleOptionVo.setConfirm(false);
                handleOptionVo.setDelete(false);
                handleOptionVo.setPay(false);
                handleOptionVo.setRebuy(false);
                handleOptionVo.setRefund(false);
            }
            if (num == 101) {
                handleOptionVo.setAftersale(false);
                handleOptionVo.setCancel(true);
                handleOptionVo.setComment(false);
                handleOptionVo.setConfirm(false);
                handleOptionVo.setDelete(false);
                handleOptionVo.setPay(true);
                handleOptionVo.setRebuy(false);
                handleOptionVo.setRefund(false);
            }
            if (num == 203) {
                handleOptionVo.setAftersale(false);
                handleOptionVo.setCancel(false);
                handleOptionVo.setComment(false);
                handleOptionVo.setConfirm(false);
                handleOptionVo.setDelete(true);
                handleOptionVo.setPay(false);
                handleOptionVo.setRebuy(false);
                handleOptionVo.setRefund(false);
            }


            return handleOptionVo;
        }


}
